
<template>
  <div>
    <div class="gva-search-box">
      <el-form
        ref="elSearchFormRef"
        :inline="true"
        :model="searchInfo"
        class="demo-form-inline"
        :rules="searchRule"
        @keyup.enter="onSubmit"
      >
        <el-form-item
          label="创建日期"
          prop="createdAt"
        >
          <template #label>
            <span>
              创建日期
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-date-picker
            v-model="searchInfo.startCreatedAt"
            type="datetime"
            placeholder="开始日期"
            :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"
          />
          —
          <el-date-picker
            v-model="searchInfo.endCreatedAt"
            type="datetime"
            placeholder="结束日期"
            :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"
          />
        </el-form-item>
        <el-form-item
          label="邀请人手机号"
          prop="inviteUserId"
        >
          <el-input
            v-model="searchInfo.inviteUserPhone"
            placeholder="搜索条件"
          />
        </el-form-item>
        <el-form-item
          label="用户手机号"
          prop="phone"
        >
          <el-input
            v-model="searchInfo.phone"
            placeholder="搜索条件"
          />
        </el-form-item>
        <el-form-item
          label="名称"
          prop="name"
        >
          <el-input
            v-model="searchInfo.name"
            placeholder="搜索条件"
          />
        </el-form-item>
        <el-form-item
          label="用户类型"
          prop="types"
        >
          <el-select
            v-model="searchInfo.types"
            clearable
          >
            <el-option
              v-for="(option,key) in typeOption"
              :key="key"
              :label="option"
              :value="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="search"
            @click="onSubmit"
          >
            查询
          </el-button>
          <el-button
            icon="refresh"
            @click="onReset"
          >
            重置
          </el-button>
          <el-button
            icon="download"
            @click="exportUserExcel"
          >
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
      >
        <!--        <el-table-column-->
        <!--          type="selection"-->
        <!--          width="55"-->
        <!--        />-->
        <el-table-column
          align="center"
          label="头像"
          width="120"
        >
          <template #default="scope">
            <CustomPic
              style="margin-top:12px"
              :pic-src="scope.row.avatar"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="名称" prop="name" width="120" />
        <el-table-column align="center" label="性别" prop="sex" width="60" >
          <template #default="{row}">
            {{ row.sex == '1'?'男':'女' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="手机号" prop="phone" width="120" />
        <el-table-column align="center" label="用户类型" prop="types" width="120" >
          <template #default="{row}">
            {{ typeOption[row.types] }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="会员到期时间" width="120" >
          <template #default="scope">{{ formatDateYmd(scope.row.expiredAt) }}</template>
        </el-table-column>
        <el-table-column align="center" label="健管师" prop="steward" width="160" />
        <el-table-column align="center" label="服务人电话" prop="stewardPhone" width="120" />
        <el-table-column align="center" label="省" prop="province" width="120" />
        <el-table-column align="center" label="市" prop="city" width="120" />
        <el-table-column align="center" label="区/县" prop="area" width="120" />
        <el-table-column align="center" label="注册日期" width="120" >
          <template #default="scope">{{ formatDateYmd(scope.row.createdAt) }}</template>
        </el-table-column>
        <el-table-column align="center" label="生日" width="120" >
          <template #default="scope">{{ formatDateYmd(scope.row.birthday) }}</template>
        </el-table-column>
        <el-table-column align="center" label="用户体质" width="120" >
          <template #default="{row}">
            {{ physiqueMap[row.physique] }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="用户积分" prop="points" width="120" />
        <el-table-column align="center" label="操作" fixed="right" min-width="360" >
          <template #default="scope">
            <el-button text type="primary" @click="openVip(scope.row)" >
              开通会员
            </el-button>
            <el-button text type="primary" @click="healthRecords(scope.row.ID)" >
              健康档案
            </el-button>
            <el-button text type="primary" @click="healthChat(scope.row.ID)" >
              健康数据
            </el-button>
            <el-button text type="primary" @click="openUserList(scope.row.ID)" >
              推广名单
            </el-button>
            <el-button text type="primary" @click="changePoints(scope.row.ID)" >
              修改积分
            </el-button>
            <el-button text type="primary" @click="updateBind(scope.row.ID)" >
              变更健管师
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="healthFlag"
      title="健康数据"
    >
      <el-table :data="healthData">
        <el-table-column
          align="left"
          label="日期"
          width="180"
        >
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column
          align="left"
          label="日期"
          width="180"
        >
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button
          type="primary"
          @click="healthFlag = false"
        >确 定</el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="userListFlag"
      title="推广名单"
    >
      <el-table :data="userListData">
        <el-table-column align="center" label="名称" prop="name" width="120" />
        <el-table-column align="center" label="用户手机号" prop="phone" min-width="120" />
        <el-table-column align="center" label="性别" width="120" >
          <template #default="{row}">
            {{ row.sex == '1'?'男':'女' }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="vip等级" prop="vip_type" width="120" >
          <template #default="scope">
            {{ filterDict(scope.row.vip_type,vipOptions) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="注册日期" width="120" >
          <template #default="scope">{{ formatDateYmd(scope.row.createdAt) }}</template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button
          type="primary"
          @click="userListFlag = false"
        >确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="healthFlag" title="健康数据" >
      <el-descriptions title="用户信息">
        <el-descriptions-item label="姓名">{{ healthRecordsInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ healthRecordsInfo.sex }}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ formatDate(healthRecordsInfo.birthday) }}</el-descriptions-item>
        <el-descriptions-item label="体质">
          {{ healthRecordsInfo.physique }}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="最近健康档案">
        <el-descriptions-item label="血型">{{ healthRecordsInfo.blood_type }}</el-descriptions-item>
        <el-descriptions-item label="血糖">{{ healthRecordsInfo.blood_sugar }}</el-descriptions-item>
        <el-descriptions-item label="血氧">{{ healthRecordsInfo.blood_oxygen }}</el-descriptions-item>
        <el-descriptions-item label="心率">
          {{ healthRecordsInfo.heart_rate }}
        </el-descriptions-item>
        <el-descriptions-item label="低压">
          {{ healthRecordsInfo.low_pressure }}
        </el-descriptions-item>
        <el-descriptions-item label="高压">
          {{ healthRecordsInfo.high_pressure }}
        </el-descriptions-item>
        <el-descriptions-item label="病症">
          {{ healthRecordsInfo.diseases.map(item=>item.disease).join(',') }}
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="体态评估">
        <el-descriptions-item
          v-for="(item,key) in healthRecordsInfo.posture"
          :key="key"
          :label="item.position"
        >{{ item.symptom.map(ii=>ii.name).join(",") }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="现病史">
        <el-descriptions-item label="现在的症状">{{ healthRecordsInfo.now_medical_history.now_symptom }}</el-descriptions-item>
        <el-descriptions-item label="正在采取的措施">{{ healthRecordsInfo.now_medical_history.now_measure }}</el-descriptions-item>
        <el-descriptions-item label="用药情况">{{ healthRecordsInfo.now_medical_history.now_situation }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="既往史">
        <el-descriptions-item label="曾经得过的病">{{ healthRecordsInfo.past_medical_history.past_symptom }}</el-descriptions-item>
        <el-descriptions-item label="采取的措施">{{ healthRecordsInfo.past_medical_history.past_measure }}</el-descriptions-item>
        <el-descriptions-item label="用药情况">{{ healthRecordsInfo.past_medical_history.past_situation }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button
          type="primary"
          @click="healthFlag = false"
        >确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="healthChatFlag"
      destroy-on-close
      width="700"
    >
      <health-chat-dom :data="healthChatInfo" />
    </el-dialog>
    <el-dialog
      v-model="dialogFormVisible"
      title="变更健管师"
    >
      <el-scrollbar height="500px">
        <el-form
          ref="elFormRef"
          :model="formData"
          label-position="right"
          :rules="rule"
          label-width="140px"
        >
          <el-form-item
            label="服务中心:"
            prop="levelOneID"
          >
            <el-select
              v-model="formData.levelOneID"
              @change="formData.service_center_id = undefined;formData.steward_id = undefined"
            >
              <el-option
                v-for="item in levelOneOptions"
                :key="item.ID"
                :label="item.nickName"
                :value="item.ID"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="服务站:"
            prop="levelTwoID"
          >
            <el-select
              v-model="formData.service_center_id"
              @change="formData.steward_id = undefined"
            >
              <el-option
                v-for="item in getLevelTwo(formData.levelOneID)"
                :key="item.ID"
                :label="item.name"
                :value="item.ID"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="健管师:"
            prop="levelThreeID"
          >
            <el-select v-model="formData.steward_id">
              <el-option
                v-for="item in getLevelThree(formData.service_center_id)"
                :key="item.hmId"
                :label="item.name"
                :value="item.hmId"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="enterDialog"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="vipFlag"
      title="开通会员"
    >
      <el-scrollbar height="500px">
        <el-form
          :model="vipFormData"
          label-position="right"
          label-width="90px"
        >
          <el-form-item
            label="用户:"
            prop="name"
          >
            <span>{{ vipFormData.name }}</span>
          </el-form-item>
          <el-form-item
            label="手机号:"
            prop="phone"
          >
            <span>{{ vipFormData.phone }}</span>
          </el-form-item>
<!--          <el-form-item-->
<!--            label="创建时间:"-->
<!--            prop="CreatedAt"-->
<!--          >-->
<!--            <span>{{ formatDate(vipFormData.CreatedAt) }}</span>-->
<!--          </el-form-item>-->
          <el-form-item
            label="vip等级:"
            prop="vip_type"
          >
            <el-select
              v-model="vipFormData.vipType"
              placeholder="请选择"
              style="width:20%"
              :clearable="true"
            >
              <el-option
                v-for="(item,key) in vipOptions"
                :key="key"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeOpenVip">取 消</el-button>
          <el-button
            type="primary"
            @click="openVipEnter"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {
  getAllUserList,
  getHealthData,
  openVipApi,
  setUserPoints,
  getHealthRecords,
  getUserInfoByID,
  updateUserInfo,
} from '@/api/fdUser'

// 全量引入格式化工具 请按需保留
import { formatDate, formatBoolean, formatDateYmd, filterDict, getDictFunc } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, nextTick } from 'vue'
import { getPhysiqueList } from '@/api/physique'
import HealthChatDom from '@/view/fdUser/components/healthChat.vue'
import { getServiceCenterList } from '@/api/user'
import { getHealthManageCenterList } from '@/api/serviceStation'
import { getAllHealthManagerList } from '@/api/fdHealthManager'
import CustomPic from '@/components/customPic/index.vue'
import { findVip } from '@/api/vip'

defineOptions({
  name: 'FdUser'
})

const vipFlag = ref(false)

const vipFormData = ref({
  ID: 0,
  name: '',
  phone: '',
  CreatedAt: '',
  vipType: ''
})

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    levelOneID: undefined,
    levelTwoID: undefined,
    levelThreeID: undefined
  }
}
const healthChatInfo = ref({})
const healthChatFlag = ref(false)

const healthChat = async(id) => {
  const res = await getHealthData({ id })
  if (res.code === 0) {
    healthChatInfo.value = res.data
    await nextTick()
    healthChatFlag.value = true
  }
}

const healthRecordsInfo = ref({})
const healthFlag = ref(false)

const healthRecords = async(id) => {
  const res = await getHealthRecords({ id })
  if (res.code === 0) {
    healthRecordsInfo.value = res.data
    healthFlag.value = true
  }
}

const changePoints = (id) => {
  ElMessageBox.prompt('请输入积分', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^\d+$/,
    inputErrorMessage: '请输入数字'
  }).then(async({ value }) => {
    const res = await setUserPoints({ id, points: value })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '修改成功!'
      })
      getTableData()
    }
  })
}

const userListData = ref([])

const userListFlag = ref(false)

const openUserList = async(id) => {
  const res = await getAllUserList({ page: 1, pageSize: 9999, inviteUserID: id })
  if (res.code === 0) {
    userListData.value = res.data.list
    userListFlag.value = true
  }
}

const healthData = ref([])

const exportUserExcel = () => {
  const queryInfo = {
    ...searchInfo.value,
  }
  if (!queryInfo.startCreatedAt) {
    delete queryInfo.startCreatedAt
  }
  if (!queryInfo.endCreatedAt) {
    delete queryInfo.endCreatedAt
  }
  if (!queryInfo.grade) {
    delete queryInfo.grade
  }

  const params = Object.keys(queryInfo).map(key => `${key}=${queryInfo[key]}`).join('&')
  const url = import.meta.env.VITE_BASE_API + '/disease/excelUserList?' + params
  window.open(url, '_blank')
}

const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})

const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

const typeOption = ref({
  1: '普通用户',
  2: '会员',
  3: '过期用户',
})

const openVip = row => {
  vipFlag.value = true
  vipFormData.value.ID = row.ID
  vipFormData.value.name = row.name
  vipFormData.value.phone = row.phone
  // vipFormData.value.CreatedAt = row.createdAt
  vipFormData.value.vipType = row.vipType

  // ElMessageBox.confirm('此操作将开通会员, 是否继续?', '提示', {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消',
  //   type: 'warning'
  // }).then(async() => {

  // })
}

const openVipEnter = async() => {
  const res = await openVipApi({ id: vipFormData.value.ID, vipType: vipFormData.value.vipType })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '开通成功!'
    })
    getTableData()
    closeOpenVip()
  }
}

const closeOpenVip = () => {
  vipFlag.value = false
  vipFormData.value = {
    ID: 0,
    name: '',
    phone: '',
    CreatedAt: '',
    vipType: ''
  }
}

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    if (searchInfo.value.grade === '') {
      searchInfo.value.grade = null
    }
    if (searchInfo.value.types === '') {
      searchInfo.value.types = null
    }
    getTableData()
  })
}

const exportExcel = () => {

}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getAllUserList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async() => {
}

// 获取需要的字典 可能为空 按需保留
setOptions()

const getLevelTwo = (one) => {
  if (!one) return []

  return levelTwoOptions.value.filter(item => item.creator === one)
}
const getLevelThree = (two) => {
  if (!two) return []
  return levelThreeOptions.value.filter(item => item.storeId === two)
}

const levelOneOptions = ref([])
const levelTwoOptions = ref([])
const levelThreeOptions = ref([])
const vipOptions = ref([])

const getOneOptions = async() => {
  const resOne = await getServiceCenterList({ page: 1, pageSize: 9999 })
  if (resOne.code === 0) {
    levelOneOptions.value = resOne.data.list
  }
  const resTwo = await getHealthManageCenterList({ page: 1, pageSize: 9999 })
  if (resTwo.code === 0) {
    levelTwoOptions.value = resTwo.data
  }
  const resThree = await getAllHealthManagerList({ page: 1, pageSize: 9999 })
  if (resThree.code === 0) {
    levelThreeOptions.value = resThree.data.list
  }
  vipOptions.value = await getDictFunc('vip')
}
getOneOptions()

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  ID: 0,
  levelOneID: undefined,
  service_center_id: undefined,
  steward_id: undefined,
})

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 更新行
const updateBind = async(id) => {
  const res = await getUserInfoByID({ id: id })
  if (res.code === 0) {
    formData.value.levelOneID = res.data.healthManager.healthManageCenter.creatorInfo.ID
    formData.value.service_center_id = res.data.healthManager.healthManageCenter.ID
    formData.value.steward_id = res.data.steward_id
    formData.value.ID = res.data.ID
    dialogFormVisible.value = true
    getLevelTwo(formData.value.levelOneID)
    getLevelThree(formData.value.service_center_id)
  }
}

const enterDialog = async() => {
  const res = await updateUserInfo(formData.value)
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '更改成功'
    })
    closeDialog()
    getTableData()
  }
}

const physiqueMap = ref({})
// 查询
const getPhysiqueListFunc = async() => {
  const res = await getPhysiqueList({ page: page.value, pageSize: 10000 })
  if (res.code === 0) {
    res.data.list.forEach(item => {
      physiqueMap.value[item.id] = item.tz_name
    })
  }
}
getPhysiqueListFunc()

</script>

<style>

</style>

